<template>
  <div>
    <LayoutContent />
    <!-- <van-action-bar>
      <van-action-bar-icon icon="home" text="首页" @click="goHome" />
    </van-action-bar> -->
  </div>
</template>


<script setup lang="ts">
  import '@/style/layout.less';

  import { storeToRefs } from 'pinia';
  import { ref, computed, onMounted, watch } from 'vue';
  import { useRoute,useRouter } from 'vue-router';
  import {MessagePlugin} from 'tdesign-vue-next'

  import { prefix } from '@/config/global';
  import { useSettingStore, useTabsRouterStore, useUserStore, useWebsocketStore } from '@/store';

  import LayoutContent from './components/LayoutContent.vue';
   



  import {saveSettings} from '@/api/settings'
  import type{settingModel} from '@/api/model/settingsModel'
  import {wxOauth,checkLogin} from '@/api/weixin'
  import $eventBus from '@/utils/eventBus';

  const route = useRoute();
  const settingStore = useSettingStore();
  const tabsRouterStore = useTabsRouterStore();
  const setting = storeToRefs(settingStore);
  const socketStore = useWebsocketStore();

  const mainLayoutCls = computed(() => [
    {
      't-layout--with-sider': settingStore.showSidebar,
    },
  ]);
  const loginBeforeEvent = ref('')
  const appendNewRoute = () => {
    const {
      path,
      query,
      meta: { title },
      name,
    } = route;
    tabsRouterStore.appendTabRouterList({
      path,
      query,
      title: title as string,
      name,
      isAlive: true,
      meta: route.meta,
    });
  };
  const userStore = useUserStore();
  const visiblePasswordSet=ref(false)
  function getUrlParam(name : any) {
    let p = window.location.toString().split('?')[1]
    let param = new URLSearchParams('?' + p)
    return param.get(name)
  }
const goHome=()=>{
  router.push('/')
}

  const loginQrcode = ref('');
  socketStore.wsConnect()
  //socketStore.sseConnect()
  const showLogin = ref(false);
  const router = useRouter();
  const openLogin = () => {
     //router.push('/login');
	 localStorage.setItem('authStep',"1")
	 console.log('openLogin authStep 1')
	 
	 checkLogin()
  };

$eventBus.on('openPasswordSet',(d:any)=>{
	visiblePasswordSet.value=true
})
  $eventBus.on('SseOpenEvent', (d: any) => {
    // if (userStore.token != null && userStore.token.length > 12) {
    //   return;
    // }
    fetchQrcode();
  });
  $eventBus.on('receiveMsgEvent', (data: string) => {

    const d = JSON.parse(data);
    if (d.type === 'login.success') {
      //userStore.login(d.data.access_token);
      //visibleQrLogin.value = false;
    }
    if (d.Type === 'login.success') {
      //APItoken请求 用户登录
      // let token=JSON.parse(d.Message).access_token
      // userStore.login(token);
      // visibleQrLogin.value = false;
      // clearInterval(loginTimer)
    }
    if (d.type === 'login.fail'||d.Type === 'login.fail') {
      // MessagePlugin.error('登录失败');
      // visibleQrLogin.value = false;
    }
    if(d.type==='api.token'||d.Type==='api.token')
    {
      let token=JSON.parse(d.Message).token
      MessagePlugin.success('token申请成功')
      let settingData=[{
          id:'',
          group:'api.token',
          key:'api.token',
          value:token
      }]
      saveSettings(settingData)
      .then(ret=>{
        $eventBus.emit('api.token.success')
      })
    }
  });
  $eventBus.on('onError',(msg:string)=>{
    console.log('onError',msg)
    MessagePlugin.error(msg)
  })

  $eventBus.on('OpenLoginEvent', () => {
     openLogin()
  });
  //升级VIP业务
    const vipDialogVisible = ref(false)
    //充值业务
    const rechargeDialogVisible = ref(false)

    $eventBus.on('OpenLoginEvent', () => {
      openLogin();
    });
    $eventBus.on('LoginSuccessEvent', () => {
      showLogin.value=false
      userStore.getUserInfo();
      userStore.getAssetInfo();
      if (loginBeforeEvent.value == 'openRecharge') {
        rechargeDialogVisible.value = true
        loginBeforeEvent.value = ''
      }
    });
    $eventBus.on("Logout", () => {
      localStorage.removeItem('token')
      userStore.getUserInfo();
    })


    $eventBus.on('openRecharge', () => {
      if (userStore.userInfo.nick === '') {
        loginBeforeEvent.value = 'openRecharge'
        openLogin();
      } else {
        rechargeDialogVisible.value = true
      }
    })
    $eventBus.on('paySuccess', () => {
      rechargeDialogVisible.value = false
      vipDialogVisible.value = false
      userStore.getAssetInfo()
    })

    $eventBus.on('openVip', () => {
      if (userStore.userInfo.user_id == '') {
        loginBeforeEvent.value = 'openVip'
        openLogin();
      } else {
        vipDialogVisible.value = true
      }
    })

   $eventBus.on('openAbout',()=>{
     visibleAbout.value=true
   })

  // 二维码登录
  const visibleQrLogin = ref(false);
  const fetchQrcode = () => {
    userStore.fetchLoginQrcode().then((ret: any) => {
      console.log('qrcode',JSON.stringify(ret))
      loginQrcode.value = ret.url;
    });

  };
  const verModel={

    newVersion:false,
    version:'',
    downloadUrl:'',
    description:'',
    database:''
  }
  const versionInfo=ref({...verModel})

  let loginTimer=setInterval(() => {
    // if(!userStore.token)
    // {
    //   userStore.fetchLoginQrcode().then((ret: any) => {
    //     console.log('qrcode',JSON.stringify(ret))
    //     loginQrcode.value = ret.url;
    //   });
    // }

    }, 60000 );


  onMounted(() => {
    let inviteCode = getUrlParam('code')
    if (inviteCode !== '' && inviteCode !== null) {
      localStorage.setItem('inviteCode', inviteCode)
    }
    appendNewRoute();

    
    checkLogin()
	userStore.getLoginInfo();
  });

  watch(
    () => route.path,
    () => {
      appendNewRoute();

      //document.querySelector(`.${prefix}-layout`).scrollTo({ top: 0, behavior: 'smooth' });
    },
  );
 </script>

<style lang="less" scoped></style>
